package com.siao.console;

import java.util.HashMap;
import java.util.Scanner;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.siao.core.ThreadService;

/**
 * @author Leon
 * 命令线程服务器（单例模式）
 */
public class Console extends ThreadService {

	private static final Logger logger = LoggerFactory.getLogger("Console");

	private static final Console instance = new Console();

	public static Console getInstance() {
		return instance;
	}

	private HashMap<String, IConsoleHandler> handlers;

	private HashMap<String, String> helps;

	private Console() {
		super("Console Server");
		this.handlers = new HashMap<String, IConsoleHandler>();
		this.helps = new HashMap<String, String>();
	}

	private void printHelp() {
		for (String cmd : this.helps.keySet()) {
			System.out.println(cmd + " - " + this.helps.get(cmd));
		}
	}

	private void quit() {
		System.exit(0);
	}

	@Override
	protected void init() throws Exception {
		System.setErr(System.out);
	}

	@Override
	protected void execute() throws Exception {
		System.out.print("#Console>");
		Scanner scanner = new Scanner(System.in);
		String input = scanner.nextLine();
		scanner.close();

		if (input.trim().equals("")) {
			return;
		}

		int i = input.indexOf(" ");
		String cmd = (i == -1) ? input.trim().toLowerCase() : input.substring(0, i).trim().toLowerCase();
		String val = (i == -1) ? "" : input.substring(i + 1).trim().toLowerCase();
		String[] vals = val.split(" ");

		if (cmd.equals("quit") || cmd.equals("exit")) {
			this.quit();
			return;
		}

		if (cmd.equals("-help")) {
			this.printHelp();
			return;
		}

		IConsoleHandler handler = this.handlers.get(cmd);
		if (handler == null) {
			System.out.println("Error Command. Please use -help to get more help");
			return;
		}

		if (vals[0].equals("help")) {
			System.out.println(this.helps.get(cmd));
			return;
		}

		try {
			handler.execute(vals);
		} catch (Throwable e) {
			logger.error("Command execute failed, cause:" + e.getMessage());
		}
	}

	@Override
	protected void exit() throws Exception {
	}

	/**
	 * 设置命令处理器
	 * @param cmd 命令字符串
	 * @param handler 命令处理器
	 */
	public void setHandler(String cmd, IConsoleHandler handler) {
		if (this.handlers.containsKey(cmd)) {
			logger.debug("Exist command '" + cmd + "'.");
			return;
		}
		this.handlers.put(cmd, handler);
		logger.debug("Add command '" + cmd + "'.");
	}

	/**
	 * 设置命令处理器
	 * @param cmd 命令字符串
	 * @param handler 命令处理器
	 * @param help 帮助信息
	 */
	public void setHandler(String cmd, IConsoleHandler handler, String help) {
		if (this.handlers.containsKey(cmd)) {
			logger.debug("Exist command '" + cmd + "'.");
			return;
		}
		this.handlers.put(cmd, handler);
		this.helps.put(cmd, help);
		logger.debug("Add command '" + cmd + "'," + help);
	}

	/**
	 * 移除命令处理器
	 * @param cmd
	 */
	public void removeHandler(String cmd) {
		if (!this.handlers.containsKey(cmd)) {
			logger.debug("Not exist command " + cmd + ".");
			return;
		}
		this.handlers.remove(cmd);
		logger.debug("Remove command '" + cmd + "'.");
	}

	/**
	 * 移除所有处理器
	 */
	public void clearHandler() {
		this.handlers = new HashMap<String, IConsoleHandler>();
		this.helps = new HashMap<String, String>();
	}

}
